package cn.com.dashihui.kit;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;

import com.jfinal.kit.StrKit;

public class CommonKit {
	
	/**
	 * 鍒ゆ柇褰撳墠璇锋眰鏄惁鏄墜鎸佽澶�
	 * @param request
	 * @return
	 */
	public static boolean isHandDev(HttpServletRequest request){
		//\b 鏄崟璇嶈竟鐣�(杩炵潃鐨勪袱涓�(瀛楁瘝瀛楃 涓� 闈炲瓧姣嶅瓧绗�) 涔嬮棿鐨勯�昏緫涓婄殑闂撮殧),
		// 瀛楃涓插湪缂栬瘧鏃朵細琚浆鐮佷竴娆�,鎵�浠ユ槸 "\\b"
		// \B 鏄崟璇嶅唴閮ㄩ�昏緫闂撮殧(杩炵潃鐨勪袱涓瓧姣嶅瓧绗︿箣闂寸殑閫昏緫涓婄殑闂撮殧)
		String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i|windows (phone|ce)|blackberry|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp|laystation portable)|nokia|fennec|htc[-_]|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";  
		String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
		
		//绉诲姩璁惧姝ｅ垯鍖归厤锛氭墜鏈虹銆佸钩鏉�
		Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
		Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
		try{
			//鑾峰彇ua锛岀敤鏉ュ垽鏂槸鍚︿负绉诲姩绔闂�
			String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();
			if(null == userAgent){
			    userAgent = "";
			}
		    //鍖归厤鎵嬫満绔�
		    Matcher matcherPhone = phonePat.matcher(userAgent);
		    //鍖归厤骞虫澘绔�
		    Matcher matcherTable = tablePat.matcher(userAgent);
		    return matcherPhone.find()||matcherTable.find();
		}catch(Exception e){}
		return false;
	}
	
	/**
	 * 创建随机一定位数的随机数
	 */
	public static String buildRandomNum(int len){
		StringBuffer random = new StringBuffer(len);
		for(int i = 0; i < len; i++){
			random.append((int)(Math.random() * 10));
		}
		return random.toString();
	}
	
	/**
	 * 
	 */
	public static boolean isAjax(HttpServletRequest request){
		String xRequestedWith = request.getHeader("X-Requested-With");
		return !StrKit.isBlank(xRequestedWith);
	}
	
	/**
	 * 获取UUID
	 */
	public static String getUUID(){
		String s = UUID.randomUUID().toString(); 
		//去掉“-”符号 
        return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); 
	}
	
	private static final String UNKNOWN = "unknown";
	private static final String LOCALHOST = "0:0:0:0:0:0:0:1";
	/**
	 * 生成指定位数的随机数字
	 */
	public static String randomNum(int len){
		StringBuffer random = new StringBuffer(len);
		for(int i = 0; i < len; i++){
			random.append((int)(Math.random() * 10));
		}
		return random.toString();
	}
	/**
	 * 生成4位随机数字
	 */
	public static String randomNum(){
		return randomNum(4);
	}
	/**
	 * 根据请求获取客户端真实ip
	 * @param request
	 * @return
	 */
	public static String getClientIp(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("HTTP_CLIENT_IP");		
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("X_FORWARDED_FOR");		
		}
		if(StrKit.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		if(LOCALHOST.equals(ip)){
			return "127.0.0.1";
		}else{
			int index = ip.indexOf(" ");
			if(index >= 0){
				ip = ip.substring(0,index);
			}
			return ip;
		}
	}
	
	/**
	 * 密码加密
	 */
	public static String encryptPassword(String passwordStr){
		return DigestUtils.md5Hex(passwordStr);
	}
	
	/**
	 * 密码对比
	 */
	public static boolean passwordsMatch(String passwordStr, String encrypted){
		if(!StrKit.isBlank(passwordStr)&&!StrKit.isBlank(encrypted)){
			return encryptPassword(passwordStr).equalsIgnoreCase(encrypted);
		}
		return false;
	}
	/**
	 * 获取时间
	 * @param format
	 * @return
	 */
	public static String getFormatDate(String format){
		if(StrKit.isBlank(format)){
			format="yyyy-MM-dd HH:mm:ss";
		}
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}
	
	/**
     * 获取一定长度的随机字符串
     * @param length 指定字符串长度
     * @return 一定长度的字符串
     */
	   public static String getRandomStringByLength(int length) {
	       String base = "abcdefghijklmnopqrstuvwxyz0123456789";
	       Random random = new Random();
	       StringBuffer sb = new StringBuffer();
	       for (int i = 0; i < length; i++) {
	           int number = random.nextInt(base.length());
	           sb.append(base.charAt(number));
	       }
	       return sb.toString();
	   }
}
